import requests
import json
import time
from openpyxl import Workbook, load_workbook
import os
import matplotlib.pyplot as plt


headers = {"X-User-Token":"756283292c03bd29dbf8a721f5ca26bc", "content-type":"application/json"}

class Save_to_excel(object):
    def __init__(self, filename, header):
        """
        :param filename: 表格文件名
        :param class_:  存储类型  如：orderlist, depth, orderlist_depth
        """
        super(Save_to_excel, self).__init__()
        self.filename = filename
        if not os.path.exists(filename):  # 判断这个文件是否已经存在，否则创建
            wb = Workbook()  # 创建文件对象
            ws = wb.active
            header_dict = {}
            for i, d in enumerate(header):
                ws[f"{chr(i+65)}1"] = d
                # 这个key在哪个列（A/B/C...）
                header_dict[d] = chr(65 + i)
            self.headers = header_dict
            wb.save(filename)  # 保存文件
        else:
            header_dict = {}
            for i, d in enumerate(header):
                # 这个key在哪个列（A/B/C...）
                header_dict[d] = chr(65 + i)
            self.headers = header_dict
        # 读取行数和列数
        wb = load_workbook(filename)
        wb.guess_types = True
        sheet = wb.active
        row = sheet.max_row
        self.row = row + 1
        wb.close()

    def insert_data(self, data_list):
        """
        :param data_list: 数据列表，里面嵌套字典，且key应该为header
        :return:
        """
        wb = load_workbook(self.filename)  # 加载已经存在的Excel文件
        wb.guess_types = True
        sheet = wb.active
        header = self.headers
        for data in data_list:
            for k in data:
                sheet[f'{header[k]}{self.row}'] = data[k]
            self.row += 1
        wb.save(self.filename)
        wb.close()

# 计数
def count_alert_history (dict_in_list):
    new_list = []
    index = 0
    for i in dict_in_list:
        i = str(i)
        new_list.append(i)
    # print(type(new_list[0]))
    new_list = list(set(new_list))
    for i in new_list:
        new_list[index] = eval(i)
        new_list[index]["count"] = dict_in_list.count(new_list[index])
        index += 1
    return new_list

# 统计一周内告警信息，参数alarm_grade是告警级别(int),时间周期可改
def one_mouth_alarminfo(type):
    now_time = int(time.time())   # 结束时间
    stime = now_time - 28*24*3600 # 28天前
    cont_alarm = {}
    for i in range(1, 5):
        etime = stime + 7*24*3600
        params = {"etime":etime, "limit":2000000000, "p":1, "nodepath":"SMY", "stime":stime, "type":type}
        time_slot = time.strftime("%m/%d", time.localtime(stime)) + "-" + time.strftime("%m/%d", time.localtime(etime))
        ret = requests.get("https://nightingale.smyoa.com/api/mon/event/his", headers=headers, params=params)
        if type == "alert":
            alert_history_list = json.loads(ret.text)['dat']['list']
            cont_sended = 0
            for i in alert_history_list:
                if "已发送" in i["status"]:
                    cont_sended += 1
            # alert_history_list = list(filter(lambda x:"已发送" in x["status"], alert_history_list))
            cont_alarm[time_slot] = cont_sended
        else:
            cont_alarm[time_slot] = json.loads(ret.text)['dat']['total']
        stime = etime + 1
    print(cont_alarm)
    return cont_alarm


# 用户
def user_get():
    ret = requests.get("https://nightingale.smyoa.com/api/uic/user?limit=10000&p=1&query=", headers=headers)
    user_list = json.loads(ret.text)['dat']['list']
    user_dict = {}
    for user in user_list:
        user_dict[user['id']]=user['dispname']
    return user_dict

# 用户组
def user_group_get():
    ret = requests.get("https://nightingale.smyoa.com/api/uic/team?limit=100000&p=1&query=", headers=headers)
    user_group_list = json.loads(ret.text)['dat']['list']
    user_group_dict = {}
    for user_group in user_group_list:
        user_group_dict[user_group['id']] = user_group['name']
    return user_group_dict

# 节点
def node_get():
    ret = requests.get("https://nightingale.smyoa.com/api/hsp/tree?query=", headers=headers)
    # print(json.loads(ret.text)['dat'][18])
    node_list = json.loads(ret.text)['dat']
    node_dict = {}
    for node in node_list:
        node_dict[node['id']] = node['path']
    return node_dict

# 拉取告警策略
def all_strategy(w_excel=False):
    ret = requests.get("https://nightingale.smyoa.com/api/mon/stra/", headers=headers)
    alarm_strategy_list = json.loads(ret.text)['dat']
    # alarm_strategy_info = alarm_strategy_list
    index = 0
    # print(alarm_strategy_list[0])
    if w_excel:
        for alarm_strategy in alarm_strategy_list:
            # 把用户id转换为用户名字
            user_index = 0
            for i in alarm_strategy['notify_user']:
                if i:
                    i = user_dict[i]
                    alarm_strategy['notify_user'][user_index] = i
                user_index += 1
            # 把用户组id转换为用户名字
            user_group_index = 0
            for i in alarm_strategy['notify_group']:
                if i:
                    i = user_group_dict[i]
                    alarm_strategy['notify_group'][user_group_index] = i
                user_group_index += 1
            # 把节点id转换为节点
            alarm_strategy['nid'] = node_dict[alarm_strategy['nid']]
            # 转换告警周期的单位
            alarm_strategy['converge'][0] = int(alarm_strategy['converge'][0])/60
            

            alarm_strategy = {x: str(alarm_strategy[x]) for x in alarm_strategy.keys() if x == "name" or x == "converge" or x == "notify_user" or x == "notify_group" or x == "nid" or x == "priority"}
            alarm_strategy_list[index] = alarm_strategy
            index +=1
            
        s = Save_to_excel("alarm.xlsx", ["name", "converge", "notify_group", "notify_user", "nid", "priority"])
        s.insert_data(alarm_strategy_list)
    else:
        return alarm_strategy_list

if __name__ == "__main__":
    alert = one_mouth_alarminfo('alert')
    recovery = one_mouth_alarminfo('recovery')

    plt.bar(x=alert.keys(), height=alert.values(), width=0.8, label="alert")
    plt.bar(x=alert.keys(), height=recovery.values(), width=0.8, label="recovery")
    plt.legend()
    plt.show()

